<template>
  <div class="todoapp">
    <TodoHeader :list="renderList" @add="add" />
    <TodoMain :list="renderList" :status="status" @del="doDel" />
    <TodoFooter :list="list" :count="list.length" @status="changeStatus" @clearDone="clearDone" />
  </div>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todoAll")) || [],
      status: '全部',
    };
  },
  // 使数据持久化
  watch: {
    list: {
      deep: true,
      handler() {
        // 把最新的list存起来
        localStorage.setItem("todoAll", JSON.stringify(this.list));
      },
    },
  },
  methods: {
    add(task) {
      const last = this.list[this.list.length - 1];
      const id = last ? last.id + 1 : 100;
      this.list.push({
        id,
        name: task,
        isDone: false,
      });
    },
    doDel(id){
      const index = this.list.findIndex(item => item.id ===id);
      this.list.splice(index, 1);
    },
    changeStatus(status){
      this.status = status;
    },
    clearDone(){
      this.list = this.list.filter(item => !item.isDone);
    },
  },
  computed: {
    renderList() {
      if (this.status === "未完成") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.status === "已完成") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
  },
};
</script>

<style>
</style>